﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using SecureCommander.Core.UserManagement;
using SecureCommander.Core.SecurityManager;
using System.Security.Cryptography;
using SecureCommander.Helper;
using SecureCommander.DataAccess;

namespace SecureCommander.GUI
{
    /// <summary>
    /// Interaction logic for FormSign.xaml
    /// </summary>
    public partial class FormSign : Window
    {
        public string StartDirectory { get; set; }
        public UserInfo User { get; set; }
        public string Passphrase { get; set; }
        
        public FormSign()
        {
            InitializeComponent();
        }

        private void btnBrowseInput_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog opendiasrc = new OpenFileDialog();
            if (opendiasrc.ShowDialog().Value)
            {
                txtInput.Text = opendiasrc.FileName;
                txtOutput.Text = txtInput.Text + ".sig";
            }
        }

        private void btnBrowseOutput_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.InitialDirectory = StartDirectory;
            saveDialog.Filter = "Signature|*.sig";
            if (saveDialog.ShowDialog().Value)
            {
                txtOutput.Text = saveDialog.FileName;
            }
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                byte[] bytes = File.ReadAllBytes(txtInput.Text);
                RijndaelAlgorithm Rij = new RijndaelAlgorithm();
                String prikey = Rij.Decrypt(User.Privatekey, Passphrase);

                RSACryptoServiceProvider Rsa = new RSACryptoServiceProvider();
                Rsa.FromXmlString(prikey);
                byte[] Hashfinal;
                HashAlgorithm hash = new SHA256Managed();
                string CryConfig = CryptoConfig.MapNameToOID("SHA256");
                Hashfinal = hash.ComputeHash(bytes);
                byte[] sig = Rsa.SignHash(Hashfinal, CryConfig);
                File.WriteAllBytes(txtOutput.Text, sig);
                FileHelper.ShowMessage("Signature successful!!", MessageBoxImage.Information);
                e.Handled = true;
                DialogResult = true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }          
        }
    }
}
